package cn.sdhuijin.healthexam.control;

import java.util.Properties;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class RadioGroupViewControl implements IControl, OnClickListener {

	private Activity activity;
	private RadioGroup radioGroup;
	private String name;
	private int radioId;

	public RadioGroupViewControl(Activity activity, int RadioGroupId,
			String name) {
		this.activity = activity;
		this.radioGroup = (RadioGroup) activity.findViewById(RadioGroupId);
		int num = this.radioGroup.getChildCount();
		for (int i = 0; i < num; i++) {
			RadioButton radioButton = (RadioButton) this.radioGroup
					.getChildAt(i);
			radioButton.setOnClickListener(this);
		}
		this.name = name;
		this.radioId = 0;
	}

	@Override
	public void getValue(Properties prop) {
		RadioButton radioButton = (RadioButton) this.activity
				.findViewById(radioGroup.getCheckedRadioButtonId());
		if (radioButton != null) {
			prop.setProperty(this.name + "_content", radioButton.getText().toString());
			prop.setProperty(this.name,
					radioGroup.indexOfChild(radioButton) + 1 + "");
		} else {
			prop.setProperty(this.name + "_content", "");
			prop.setProperty(this.name, "");
		}
	}

	@Override
	public void setValue(Properties prop) {
		String value = prop.getProperty(this.name + "_content");
		if (value != null) {
			int num = this.radioGroup.getChildCount();
			for (int i = 0; i < num; i++) {
				RadioButton radioButton = (RadioButton) this.radioGroup
						.getChildAt(i);
				if (radioButton.getText().toString().equals(value)) {
					Log.e("RadioGroupViewControl", "value = " + value);
					this.radioGroup.check(radioButton.getId());
					radioId = radioButton.getId();
					break;
				}
			}
		}
	}

	@Override
	public void onClick(View v) {
		if (radioId == radioGroup.getCheckedRadioButtonId()) {
			radioGroup.clearCheck();
			radioId = 0;
		} else {
			radioId = radioGroup.getCheckedRadioButtonId();
		}
	}
}
